﻿using BaseUI;
using BLL;
using Model;
using System;
using System.Data;
using System.Web.UI.WebControls;
using Utility.Helper;

namespace Thksoft.BusinessExpansion.Templete
{
    public partial class BasisSettings : BasePage
    {
        private Qs_Base_SetBLL qbb = new Qs_Base_SetBLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.Params["TYPE"] == "API")
                {
                    var data = AjaxResult.GetPostData(this.Context);
                    /*
                    if (data["Type"].NewToObject<string>() == "GET_PAGE")
                    {
                        var reson = new JObject();
                        var pageSize = data["PAGE_SIZE"].NewToObject<int>();
                        var currentPage = data["CURRENT_PAGE"].NewToObject<int>();
                        var cmyId = data["COMPANY_ID"].NewToObject<int>();
                        if (currentPage == 1)
                        {
                            reson["Count"] = bll.GetDataByCount(cmyId);
                        }
                        reson["Data"] = bll.GetDataByPage(cmyId, (currentPage - 1) * pageSize, pageSize).ToJToken();
                        AjaxResult.Success(this.Context, reson);
                        return;
                    }*/
                    if (data["Type"].NewToObject<string>() == "SAVE")
                    {
                        var entity = data["Data"].NewToObject<Qs_Base_Set>();
                        qbb.UpdateModel(entity, lognUser.USER_NAME);
                        AjaxResult.Success(this.Context, entity);
                        return;
                    }
                    if (data["Type"].NewToObject<string>() == "ADD")
                    {
                        var entity = data["Data"].NewToObject<Qs_Base_Set>();

                        qbb.InsertModel(entity, lognUser.USER_NAME);
                        AjaxResult.Success(this.Context, entity);
                        return;
                    }
                    if (data["Type"].NewToObject<string>() == "GET_INFO")
                    {
                        var id = data["ID"].NewToObject<string>();
                        var entity = qbb.GetModelById(id);
                        AjaxResult.Success(this.Context, entity);
                        return;
                    }
                    if (data["Type"].NewToObject<string>() == "GET_INFO_NAME")
                    {
                        var name = data["NAME"].NewToObject<string>();
                        var entity = qbb.GetModelByName(name);
                        AjaxResult.Success(this.Context, entity);
                        return;
                    }
                    if (data["Type"].NewToObject<string>() == "DELETE")
                    {
                        var id = data["ID"].NewToObject<string>();
                        var entity = qbb.GetModelById(id);
                        if (entity != null)
                        {
                            qbb.Delete(id.ToString(), lognUser.USER_NAME);
                        }
                        else
                        {
                            AjaxResult.Reson(this.Context, 0, null, "当前数据已删除");
                            return;
                        }
                        AjaxResult.Success(this.Context);
                        return;
                    }
                    return;
                }
                Bind();
            }
        }

        private void Bind()
        {
            string whereStr = "";
            string key = txtKey.Text.Trim();

            if (!string.IsNullOrEmpty(key))
            {
                whereStr = " AND b.Set_name like '%" + key + "%'";
            }
            ViewState["Where"] = whereStr;

            BindData(true);
        }

        private void BindData(bool isFirst)
        {
            string Where = "";
            try
            {
                Where = ViewState["Where"].ToString();
            }
            catch
            {
                Where = "";
            }

            int rowcount = 0;
            if (isFirst)
            {
                PageIng.CurrentPage = 1;
            }
            rowcount = qbb.GetRecordCount(Where);

            DataTable dtItem;

            dtItem = qbb.GetListByPage(Where, "Set_id", PageIng.CurrentPage, PageIng.RowsPerPage);

            if (dtItem != null && dtItem.Rows.Count > 0)
            {
                PageIng.Visible = true;
                PageIng.RowsCount = rowcount;
                PageIng.DataSource = dtItem;
                PageIng.GridViewSource = grvShow;
                PageIng.RowsPerPage = PageIng._rowsPerPage;
                PageIng.Bind();
            }
            else
            {
                PageIng.DataSource = dtItem;
                PageIng.GridViewSource = grvShow;
                grvShow.DataSource = null;
                grvShow.DataBind();
                PageIng.Visible = false;
            }
        }

        protected void btnInsert_Click(object sender, EventArgs e)
        {
            //Response.Redirect("/BusinessExpansion/Templete/Add_BasisSettings.aspx");
            MessageBox.ResponseScript(this, "FORM_INSERT();");
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            int count = 0;
            for (int i = 0; i < grvShow.Rows.Count; i++)
            {
                if (((CheckBox)grvShow.Rows[i].FindControl("chkSelectId")).Checked == true)
                {
                    count++;
                    if (count == 1)
                    {
                        string pid = ((CheckBox)grvShow.Rows[i].FindControl("chkSelectId")).ToolTip;//((HiddenField)grvShow.Rows[i].FindControl("HiddID")).Value.ToString();
                        MessageBox.ResponseScript(this, "FORM_EDIT(\"" + pid + "\");");
                        return;
                    }
                }
            }
        }

        protected void btnSelect_Click(object sender, EventArgs e)
        {
            Bind();
        }

        protected void DeleteClick(object sender, EventArgs e)
        {
            var ids = "";
            for (int i = 0; i < grvShow.Rows.Count; i++)
            {
                if (((CheckBox)grvShow.Rows[i].FindControl("chkSelectId")).Checked == true)
                {
                    string pid = ((CheckBox)grvShow.Rows[i].FindControl("chkSelectId")).ToolTip;
                    ids += pid + ",";
                }
            }
            if (ids.Length > 0)
            {
                ids = ids.Substring(0, ids.Length - 1);
                if (qbb.Delete(ids, CurrentUserName) > 0)
                {
                    Bind();
                    MessageBox.Show(this, "【温馨提示】 删除成功");
                    return;
                }
                MessageBox.Show(this, "【温馨提示】 删除异常！");
            }
            else
            {
                MessageBox.Show(this, "【温馨提示】 你没有选择任何一项");
            }
        }

        protected void PageIng_DataBinding(object sender, EventArgs e)
        {
            BindData(false);
        }

        /// <summary>
        /// GridView 标题排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvShow_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sPage = e.SortExpression;
            string SortOrder, OrderDire;
            SortOrder = ViewState["SortOrder"] == null ? null : (string)ViewState["SortOrder"];
            OrderDire = ViewState["OrderDire"] == null ? null : (string)ViewState["OrderDire"];
            if (SortOrder == sPage)
            {
                if (OrderDire == "Desc")
                    OrderDire = "ASC";
                else
                    OrderDire = "Desc";
            }
            else
            {
                SortOrder = e.SortExpression;
                OrderDire = "ASC";
            }
            ViewState["SortOrder"] = SortOrder;
            ViewState["OrderDire"] = OrderDire;
            BindProjectName(true);
        }

        /// <summary>
        /// 绑定项目名称（非动态）绑定GridView
        /// </summary>
        public void BindProjectName(bool iSsort)
        {
            string Where = "";
            try
            {
                Where = ViewState["Where"].ToString();
            }
            catch
            {
                Where = "";
            }

            int rowcount = 0;

            rowcount = qbb.GetRecordCount(Where);

            DataTable dtItem;

            dtItem = qbb.GetListByPage(Where, "Set_id", PageIng.CurrentPage, PageIng.RowsPerPage);

            DataView view = dtItem.DefaultView;
            if (iSsort)
            {
                string sort = (string)ViewState["SortOrder"] + " " + (string)ViewState["OrderDire"];
                view.Sort = sort;//设置排序
            }

            grvShow.DataSource = view;

            grvShow.DataBind();
        }
    }
}